package edu.uab.enronemail.request;

import java.io.IOException;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentFactory;

public class DocumentLoader {
	
	BulkRequestBuilder bulkRequest = null;
	static DocumentLoader loader = null;
	Client client = null;
	static final int batch_size = 1000;
	
	private DocumentLoader(Client client){
		bulkRequest = client.prepareBulk();
		this.client = client;
	}
	
	public static DocumentLoader getDocumentLoader(Client client){
		if(loader == null) loader = new DocumentLoader(client);
		return loader;
	}
	
	static int id = 0;
	
	public static int value = 0;
	
	public void completeBulkExecution(){
		bulkInsert();
	}
	
	private void bulkInsert(){
		System.out.println("Executing Bulk Insert");
		Thread thread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				bulkRequest.execute(new ActionListener<BulkResponse>() {
				
				@Override
				public void onResponse(BulkResponse response) {
				}
				
				@Override
				public void onFailure(Throwable e) {
					
				}
			});

			}
		});
		thread.start();
		while(thread.isAlive()){
			try {
				Thread.sleep(3000);
				System.out.println("Sleeping here");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		};
	}
	public void addDocument(EmailDocument emailDoc){
		id++;
		
		try {
			bulkRequest.add(client.prepareIndex("emailrepository", "email", String.valueOf(id)).setSource(
						XContentFactory.jsonBuilder().startObject()
							.field("from" , emailDoc.findValueForField(EmailDocument.FROM_FIELD))
							.array("to", emailDoc.findValueForField(EmailDocument.TO_FIELD).split(EmailDocument.DELIMITTER))
							.array("cc", emailDoc.findValueForField(EmailDocument.CC_FIELD).split(EmailDocument.DELIMITTER))
							.array("bcc", emailDoc.findValueForField(EmailDocument.BCC_FIELD).split(EmailDocument.DELIMITTER))
							.field("subject", emailDoc.findValueForField(EmailDocument.SUBJECT_FIELD))
							.field("body",emailDoc.findValueForField(EmailDocument.BODY))
							.array("bodyTokens", emailDoc.getEmailBodyTokens())
					));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(id % batch_size == 0){
			bulkInsert();
		}
	}
}
